package com.gitee.andy.zpush.kernel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TcpClient {

	private static final Logger log = LoggerFactory.getLogger(TcpClient.class);

	private EventLoopGroup group;
	private Bootstrap bootstrap;

	public TcpClient(int nThreads, ChannelInitializer<SocketChannel> adapter) {
		group = new NioEventLoopGroup(nThreads);
		bootstrap = new Bootstrap();
		bootstrap.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(adapter);
	}

	public Session  connect(String host, int port){
    	try {
			return new Session4Client(bootstrap, bootstrap.connect(host, port).sync().channel());
		} catch (InterruptedException e) {
			log.error("", e);
			throw new RuntimeException(e);
		}
    }

	public void shutdown() {
		group.shutdownGracefully();
	}
}